<?php

use framework\libraries\Controller;
use framework\libraries\ErrorType;
use framework\support\Request;
use framework\support\Response;
use framework\support\Db;


class user extends Controller
{
    function code_get()
    {
        $code = $this->get("code");

        if (!$code) {
            return $this->error(ErrorType::MISSING_PARAMETER, "code");
        }
        $row = Db::get("code", "*", ["code" => $code]);
        if (!$row) {
            return $this->error(404001, "激活码无效或已使用");
        }
        $this->success([
            'code' => $row['code'],
            'expire_time' => $row['expire_time'],
            'is_valid' => $row['expire_time'] > date("Y-m-d H:i:s") && $row['used_time'] == null
        ]);
    }

    function active()
    {
        $code = $this->post("code");
        if (!$code) {
            return $this->error(40401, "code is null");
        }
        $row = Db::get("code", "*", ["code" => $code]);
        if (!$row) {
            return $this->error(404002, "激活码无效或已使用");
        }
        if ($row['used_time'] >= '2004-10-01') {
            return $this->error(404003, "激活码已使用");
        }
        if ($row['expire_time'] < date("Y-m-d H:i:s")) {
            return $this->error(404003, "激活码已过期");
        }
        Db::update("code", ["used_time" => date("Y-m-d H:i:s")], ["code" => $code, 'used_time' => null]);
        return  $this->success("激活成功");
    }
}
